const { BrowserWindow, ipcMain, clipboard, screen, Menu, MenuItem, dialog, ipcRenderer } = require("electron");
const path = require('path');
const mTool = require('../Tool/mTool');
const mFileTool = require('../Tool/mFileTool');
const robot = require('robotjs');
const mEmitter = require("../Manager/eventEmitter");

let filePaths;//线路文档的路径对象
let filePathIndex = 0;//线路文档的路径索引
let createQR_MainWindow;//'生成二维码'的主窗口对象

// 打开草料二维码网页
function createWindow() {
  //创建窗口
  createQR_MainWindow = new BrowserWindow({
    x: 100,
    y: 10,
    width: 900,
    height: 700,
    alwaysOnTop: true,
    show: false,
    autoHideMenuBar: true,
    backgroundColor: '#f0ffff',
    title: "计调辅助工具",
    // webPreferences: {
    //   preload: path.join(__dirname, 'preload.js')
    // }
  })

  // filePaths.forEach(filePath => {
  //   console.log(path.basename(filePath));
  // })
  // console.log(JSON.stringify(filePaths));

  // 加载 index.html
  // mainWindow.loadFile('index.html')
  createQR_MainWindow.loadURL('https://cli.im/')

  createQR_MainWindow.once("ready-to-show", () => {
    createQR_MainWindow.show();

  })

  //监听网页加载完成事件
  createQR_MainWindow.webContents.on('did-finish-load', () => {
    // setInterval(() => {
    //   console.log(robot.getMousePos());
    // },1000)
    let webTitle = createQR_MainWindow.webContents.getTitle();
    console.log(`网页的标题:${webTitle}`);

    //13078478203
    //Jing.M823
    if (webTitle === "草料二维码生成器") {
      createQR_MainWindow.webContents.executeJavaScript(`document.querySelector("#login_join > a.noLoginBox.new-header-btn.login_btn").click()`);
      createQR_MainWindow.webContents.executeJavaScript(`let iframeM=setInterval(()=>{if (document.querySelector("#iframe")) {
            clearInterval(iframeM);const loginDom=document.querySelector("#iframe");
            loginDom.addEventListener("load", () => {
              loginDom.contentDocument.querySelector('#loginemail').value = "13078478203";
              loginDom.contentDocument.querySelector("#loginpassword").value = "Jing.M823";
              loginDom.contentDocument.querySelector("#login-btn").click();
            });
          }},200);`);
    } else if (webTitle === "二维码管理中心") {
      //点击"活码"菜单
      // mainWindow.webContents.executeJavaScript(`${mTool.createDomMonitor_IsExist("a_herf", "document.querySelectorAll('.ant-menu-item')[1].children[0]", "document.querySelectorAll('.ant-menu-item')[1].children[0].click();document.querySelector('.ant-notification-notice-close').click();", 200)}`);
      createQR_MainWindow.webContents.setWindowOpenHandler((handler) => {
        const response = dialog.showMessageBoxSync(createQR_MainWindow, {
          type: 'info',
          buttons: ['确认', '取消'],
          title: '自动生码',
          message: "是否开始自动生码?",
          defaultId: 0,
          cancelId: 1,
        });

        // 根据用户选择（response）决定是否允许创建新窗口
        if (response === 0) {
          //选择线路文档
          filePaths = mFileTool.openFileSelectorSync(createQR_MainWindow)
          if (filePaths == null) {
            mEmitter.emit("displayMainWindow");
            createQR_MainWindow.close();
            return;
          }
          console.log(handler.url);
          //打开'生码'界面,开始自动生码
          openCreateQR_Window(createQR_MainWindow, handler);
        }
        return { action: 'deny' };
      })


      //   mainWindow.loadURL('https://cli.im/activecode/list');
      // mainWindow.webContents.on('context-menu', (e, params) => {
      //   // const menu = new Menu();
      //   // menu.append(new MenuItem({
      //   //   label: '开始生成二维码',
      //   //   click: () => {
      //   //     // setTimeout(() => {
      //   //     //点击"空白生码"
      //   //     mainWindow.webContents.setWindowOpenHandler((handler) => {
      //   //       openCreateQR_Window(mainWindow, handler);
      //   //       return { action: 'deny' }
      //   //     })
      //   //     // mainWindow.webContents.executeJavaScript(`setTimeout(()=>{const mouseoverEvent = new MouseEvent('mouseover', {bubbles: true,cancelable: true,view: window});document.querySelectorAll('.ant-dropdown-trigger')[1].dispatchEvent(mouseoverEvent);
      //   //     // ${mTool.createDomMonitor_IsExist("creatQR_Monitor", "document.querySelectorAll('.ant-dropdown-menu-item')[0]", "document.querySelectorAll('.ant-dropdown-menu-item')[0].click()")}},100)`);
      //   //     // }, 2000);
      //   //   }
      //   // }))

      //   // menu.popup(mainWindow, params.x, params.y);
      // })


    }

  })

  // 打开开发工具
  // mainWindow.webContents.openDevTools()

  return createQR_MainWindow;
}

let createQR_Window;
//打开"生成二维码"页面
function openCreateQR_Window(mainWindow, handler) {
  //"生成二维码"窗口
  createQR_Window = new BrowserWindow({
    x: 0,
    y: 100,
    // fullscreen: true,
    width: 1706,
    height: 700,
    parent: mainWindow,
    modal: true,
    alwaysOnTop: true,
    autoHideMenuBar: true,
    backgroundColor: '#f0ffff',
    webPreferences: {
      preload: path.join(__dirname, 'script/createQR_preload.js')
    }
  })

  createQR_Window.webContents.session.on('will-download', (event, item, webContents) => {
    // 无需对话框提示， 直接将文件保存到路径
    let saveFileName = item.getFilename().match('【.*?出发】')[0].replace('【', '').replace('出发】', '') + item.getFilename().substring(item.getFilename().lastIndexOf('.'));
    let savePath = path.join(path.dirname(filePaths[0]), '二维码');
    let dirIsExist = mFileTool.ensureDirExists(savePath, false);
    if (!dirIsExist) {
      return;
    }
    item.setSavePath(`${savePath}${path.sep}${saveFileName}`)
    // item.setSavePath(`C:${path.sep}Users${path.sep}QF${path.sep}Desktop${path.sep}testdoc${path.sep}ee${path.sep}${saveFileName}`)

    //文件下载状态
    item.on('updated', (event, state) => {
      if (state === 'interrupted') {
        console.log('下载中断')
      } else if (state === 'progressing') {
        if (item.isPaused()) {
          console.log('Download is paused')
        } else {
          // console.log(`Received bytes: ${item.getReceivedBytes()}`)
        }
      }
    })
    item.once('done', (event, state) => {
      if (state === 'completed') {
        console.log('Download successfully')
        console.log(item.savePath)

        //重新打开"生成二维码"页面
        filePathIndex++;
        if (filePathIndex >= filePaths.length) {
          createQR_Window.close();
          createQR_MainWindow.close();
          mEmitter.emit('displayMainWindow');
        }
        createQR_Window.loadURL(handler.url)
      } else {
        console.log(`Download failed: ${state}`)
      }
    })
  })
  createQR_Window.webContents.on('context-menu', (e, params) => {
    const menu = new Menu();
    menu.append(new MenuItem({
      label: '重新加载',
      click: () => {
        createQR_Window.reload();
      }
    }))
    menu.popup(createQR_Window, params.x, params.y);
  })

  createQR_Window.on('closed', () => { mainWindow.show() })
  createQR_Window.loadURL(handler.url);
  //当生码界面打开时,主页面关闭
  createQR_Window.once('ready-to-show', () => { mainWindow.minimize(); createQR_Window.show(); })

  createQR_Window.webContents.on('did-finish-load', () => {
    //写入文件路径到剪切板
    clipboard.writeText(filePaths[filePathIndex]);
    //给渲染页面添加脚本文件
    mTool.addScript2Web(createQR_Window.webContents, path.join(__dirname, "script/createQR_Web.js"));
    // createQR_Window.webContents.executeJavaScript(`${mTool.createDomMonitor_IsExist("upFileBtn","document.querySelector('#topNavWrapper > ul > li:nth-child(4)')","setTimeout(() => {document.querySelector('#topNavWrapper > ul > li:nth-child(4)').click()}, 500)",200)}`);

  })

  //监听'插入文件'按钮并移动鼠标点击按钮
  ipcMain.on('insertFileBtnPoiint', (event, x, y) => {
    robot.moveMouse(0, 0);
    //输入原生事件,模拟用户点击
    createQR_Window.webContents.sendInputEvent({
      type: 'mouseDown',
      x: x,
      y: y,
      button: 'left',
      clickCount: 1,
    });
    createQR_Window.webContents.sendInputEvent({
      type: 'mouseUp',
      x: x,
      y: y,
      button: 'left',
      clickCount: 1,
    });
    // robot.updateScreenMetrics(robot.getScreenSize());//更新屏幕尺寸信息
    // var scaleFactor = screen.getPrimaryDisplay().scaleFactor;
    // var moveX = (x + createQR_Window.getBounds().x) * scaleFactor;
    // var moveY = (y + createQR_Window.getBounds().y + 20) * scaleFactor;//50为标题栏高度
    // // console.log(`视口尺寸{${xx}==${xxx}}`);
    // // console.log(`X:${x},Y:${y}`);
    // // console.log(`moveX:${moveX},moveY:${moveY}`);
    // // console.log(screen.dipToScreenPoint({ x: moveX, y: moveY }));

    //等待文件选择框出现,并粘贴文件路径及确认
    setTimeout(() => {
      robot.keyTap('v', ['control'])
      robot.keyTap('enter');
    }, 1500)
  })

}

//****************进程间通信****************

ipcMain.handle('routeFilePath', () => {
  return path.basename(filePaths[filePathIndex]);
})

module.exports = {
  createWindow
}